package vip.xiaonuo.pm.modular.product.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollStreamUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import vip.xiaonuo.common.enums.CommonSortOrderEnum;
import vip.xiaonuo.common.exception.CommonException;
import vip.xiaonuo.common.page.CommonPageRequest;
import vip.xiaonuo.common.param.DeleteByIdParam;
import vip.xiaonuo.pm.modular.product.entity.PmProductEntity;
import vip.xiaonuo.pm.modular.product.mapper.PmProductMapper;
import vip.xiaonuo.pm.modular.product.param.ProductAddParam;
import vip.xiaonuo.pm.modular.product.param.ProductEditParam;
import vip.xiaonuo.pm.modular.product.param.ProductPageParam;
import vip.xiaonuo.pm.modular.product.service.PmProductService;

import java.util.List;

/**
 * <p>
 * 产品表 服务实现类
 * </p>
 *
 * @author xhs
 * @since 2025-06-04
 */
@Service
public class PmProductServiceImp extends ServiceImpl<PmProductMapper, PmProductEntity> implements PmProductService {

    /**
     * 根据ID查询数据
     *
     * @param id 入参
     * @return PmProductEntity
     */
    @Override
    public PmProductEntity queryEntityById(String id) {
        PmProductEntity productEntity = this.getById(id);
        if (ObjectUtil.isEmpty(productEntity)) {
            throw new CommonException("产品不存在，id值为：{}", id);
        }
        return productEntity;
    }

    /**
     * 新增产品
     *
     * @param productAddParam 入参
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void add(ProductAddParam productAddParam) {
        // 1.校验是否存在
        checkParam(productAddParam);
        PmProductEntity product = BeanUtil.toBean(productAddParam, PmProductEntity.class);
        this.save(product);
    }

    private void checkParam(ProductAddParam productAddParam) {
        boolean hasProduct = this.count(new LambdaQueryWrapper<PmProductEntity>()
                .eq(PmProductEntity::getProductName, productAddParam.getProductName())
        ) > 0;
        if (hasProduct) {
            throw new CommonException("存在重复的产品，名称为：{}", productAddParam.getProductName());
        }
    }

    /**
     * 编辑产品
     *
     * @param productEditParam 入参
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void edit(ProductEditParam productEditParam) {
        // 1.校验是否存在
        checkParam(productEditParam);
        // 2.查询数据
        PmProductEntity productEntity = queryEntityById(productEditParam.getId());
        // 3.更新数据
        BeanUtil.copyProperties(productEditParam, productEntity);
        this.updateById(productEntity);
    }

    private void checkParam(ProductEditParam productEditParam) {
        boolean hasProduct = this.count(new LambdaQueryWrapper<PmProductEntity>()
                .ne(PmProductEntity::getId, productEditParam.getId())
                .eq(PmProductEntity::getProductName, productEditParam.getProductName())
        ) > 0;
        if (hasProduct) {
            throw new CommonException("存在重复的产品，名称为：{}", productEditParam.getProductName());
        }
    }

    /**
     * 删除产品
     *
     * @param DeleteIdParamList 入参
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delete(List<DeleteByIdParam> DeleteIdParamList) {
        // 执行删除
        this.removeByIds(CollStreamUtil.toList(DeleteIdParamList, DeleteByIdParam::getId));
    }

    /**
     * 获取产品分页
     *
     * @param productPageParam 入参
     * @return Page<PmProductEntity>
     */
    @Override
    public Page<PmProductEntity> page(ProductPageParam productPageParam) {
        QueryWrapper<PmProductEntity> queryWrapper = new QueryWrapper<PmProductEntity>().checkSqlInjection();
        queryWrapper.lambda()
                .and((StringUtils.hasLength(productPageParam.getSearchKey())), q ->
                        q.like(StringUtils.hasLength(productPageParam.getSearchKey()), PmProductEntity::getProductName, productPageParam.getSearchKey())
                                .or()
                                .like(StringUtils.hasLength(productPageParam.getSearchKey()), PmProductEntity::getProductCode, productPageParam.getSearchKey())
                )
                .eq(StringUtils.hasLength(productPageParam.getProductOwner()), PmProductEntity::getProductOwner, productPageParam.getProductOwner());
        // 处理排序
        if (ObjectUtil.isAllNotEmpty(productPageParam.getSortField(), productPageParam.getSortOrder())) {
            CommonSortOrderEnum.validate(productPageParam.getSortOrder());
            queryWrapper.orderBy(true, productPageParam.getSortOrder().equals(CommonSortOrderEnum.ASC.getValue()),
                    StrUtil.toUnderlineCase(productPageParam.getSortField()));
        } else {
            queryWrapper.lambda().orderByAsc(PmProductEntity::getSortCode);
        }
        return this.page(CommonPageRequest.defaultPage(), queryWrapper);
    }
}
